<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<!-- <a-breadcrumb separator=">" class="mb-4 pl-[10px]">
			<a-breadcrumb-item>合同管理</a-breadcrumb-item>
			<a-breadcrumb-item><a href="">合同管理</a></a-breadcrumb-item>
		</a-breadcrumb> -->
		<div class="flex justify-between items-center">
			<a-space :size="16">
				<a-input-group compact>
					<a-select v-model:value="searchType" style="width: 150px" @change="searchText = ''">
						<a-select-option :value="0">甲方抬头</a-select-option>
						<a-select-option :value="1">申请编号</a-select-option>
					</a-select>
					<a-input
						v-model:value="searchTextComputed"
						style="width: 200px"
						placeholder="请输入关键字搜索"
						@pressEnter="table.clearRefreshSelected(true)"
					></a-input>
				</a-input-group>
				<a-select
					placeholder="请选择创建人"
					v-model:value="searchOption.createUser"
					class="w-[200px]"
					:options="userList"
					:filter-option="false"
					allowClear
					showSearch
					@search="searchCreater"
					@change="changeCreater"
				></a-select>
				<a-button type="primary" @click="table.refresh(true)">查询</a-button>
				<a-button @click="screenVisible = true">更多筛选</a-button>
			</a-space>
		</div>
	</a-card>
	<!-- 表格展示区域 -->
	<!--	class="h-full"-->
	<a-card :bordered="false">
		<a-space v-if="hasPerm('bizFinancePaymentExport')" :size="16" class="mb-6">
			<div>批量操作</div>
			<a-button type="primary" @click="toBatchExport">批量导出</a-button>
		</a-space>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'signPayment'">
					<span>{{ signPayEnum[record.signPayment] }}</span>
				</template>
				<template v-if="column.dataIndex === 'financeApprovalStatus'">
					<span>{{ approvalStatusEnum[record.financeApprovalStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'imgUrl'">
					<span v-if="record.imgUrl" type="link" class="text-blue-500 cursor-pointer" @click="onPreview(record.imgUrl)"
						>查看</span
					>
					<span v-else>-</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-popover placement="left">
						<template #content>
							<div class="flex flex-col">
								<a-button v-if="hasPerm('bizFinancePaymentView')" type="link" @click="onDetail(record.id)">
									查看详情
								</a-button>
								<a-button
									type="link"
									v-if="
										hasPerm('bizFinancePaymentApprove') && record.financeApprovalStatus === 'PendingFinancialApproval'
									"
									@click="approve(record)"
									>补款审批</a-button
								>
							</div>
						</template>
						<a>操作</a>
					</a-popover>
				</template>
			</template>
			<template #expandedRowRender="{ record }">
				<a-table
					:columns="childColumns"
					:data-source="record.list"
					:pagination="false"
					bordered
					row-key="id"
					size="small"
					class="my-[10px]"
					:scroll="{ x: 1200 }"
				/>
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal
		v-model:visible="screenVisible"
		title="更多筛选"
		:footer="null"
		:closable="false"
		:width="500"
		@cancel="cancelMoreSearch"
	>
		<a-form :label-col="labelCol">
			<a-form-item label="补款合计">
				<a-input-group compact>
					<a-select style="width: 30%" v-model:value="moreSearch.receivedOperators" placeholder="请选择">
						<a-select-option value="gt">></a-select-option>
						<a-select-option value="eq">=</a-select-option>
						<a-select-option value="lt">&lt;</a-select-option>
					</a-select>
					<a-input-number style="width: 70%" v-model:value="moreSearch.receivedAmount" placeholder="请输入" />
				</a-input-group>
			</a-form-item>
			<a-form-item label="签约方式">
				<a-select
					v-model:value="moreSearch.signMethod"
					:options="signMethodOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="签约场景">
				<a-select
					v-model:value="moreSearch.signPayment"
					:options="signPayOptions"
					placeholder="请选择"
					allow-clear
				></a-select>
			</a-form-item>
			<a-form-item label="合同模板">
				<a-select
					v-model:value="moreSearch.templateId"
					:options="templateOptions"
					placeholder="请选择"
					allow-clear
				></a-select>
			</a-form-item>
			<a-form-item label="审批状态">
				<a-select
					v-model:value="moreSearch.financeApprovalStatus"
					:options="appStatusOptions"
					placeholder="请选择"
					allow-clear
				></a-select>
			</a-form-item>
			<a-form-item label="签约日期">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.signingDate"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
			<a-form-item label="创建日期">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.createDate"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
			<a-form-item label="乙方抬头">
				<a-select v-model:value="moreSearch.secondPartyId" :options="partyOptions" placeholder="请选择" allow-clear />
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="clearSearch">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="doMoreSearch">筛选</a-button>
				<a-button @click="cancelMoreSearch">取消</a-button>
			</a-space>
		</div>
	</a-modal>

	<!-- 补款审批 -->
	<approve-modal v-model:visible="approveVisible" v-if="approveVisible" :info="info" @finished="table.refresh(true)" />

	<!-- 查看付款凭证 -->
	<image-preview ref="imagePreviewRef" />
</template>
<script setup>
	import ApproveModal from './approveModal.vue'
	import contractApi from '@/api/biz/bizContractApi'
	import financePaymentApi from '@/api/biz/payment/bizFinancePaymentApi'
	import usersApi from '@/api/biz/bizUserApi'
	import {
		signPayOptions,
		signPayEnum,
		appStatusOptions,
		approvalStatusEnum,
		signMethodOptions,
		signMethodEnum
	} from '../contractManagement/enum/contractEnum'
	import ImagePreview from '@/components/drawer/imagePreview.vue'
	import tool from '@/utils/tool'
	import downloadUtil from '@/utils/downloadUtil'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'

	const router = useRouter()
	const tableCache = useTableCache('financePayment', ['bizFinancePayment', 'bizFinancePaymentDetail'])

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			searchType.value = tableCacheData.searchType
			searchText.value = tableCacheData.searchText
			searchOption.value = tableCacheData.searchOption
			moreSearch.value = tableCacheData.moreSearch
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}

		getContractPartbList()
		getTemplates()
		getCreaters()
	})
	const columns = [
		{
			title: '申请编号',
			dataIndex: 'payCode',
			width: 180,
			align: 'center',
			fixed: 'left'
		},
		{
			title: '合同模板',
			dataIndex: 'templateName',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '甲方抬头',
			dataIndex: 'firstParty',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '乙方抬头',
			dataIndex: 'secondPartyName',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '签约方式',
			dataIndex: 'signMethod',
			width: 150,
			align: 'center',
			customRender: ({ text }) => signMethodEnum[text] || '-'
		},
		{
			title: '签约场景',
			dataIndex: 'signPayment',
			width: 150,
			align: 'center'
		},
		{
			title: '补款合计',
			dataIndex: 'receivedAmount',
			width: 100,
			align: 'center'
		},
		{
			title: '审批状态',
			dataIndex: 'financeApprovalStatus',
			align: 'center',
			width: 100
		},
		{
			title: '驳回原因',
			dataIndex: 'rejectReason',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '付款日期',
			dataIndex: 'payDate',
			width: 150,
			align: 'center',
			customRender: ({ text }) => text || '-'
		},
		{
			title: '付款凭证',
			dataIndex: 'imgUrl',
			align: 'center',
			width: 100
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '提交人',
			dataIndex: 'createUserName',
			width: 120,
			align: 'center'
		},
		{
			title: '提交时间',
			dataIndex: 'createAt',
			width: 150,
			align: 'center'
		}
	]
	const childColumns = [
		{
			title: '订单编号',
			dataIndex: 'orderNo',
			width: 200,
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '业务类型',
			dataIndex: 'businessType',
			width: 80,
			customRender: ({ text }) => tool.dictTypeData('BUSINESS_TYPE', text)
		},
		{
			title: '服务类型',
			dataIndex: 'serviceTypeName',
			width: 180,
			ellipsis: true,
			customRender: ({ text, record }) => `${record.serviceClassName} > ${text} > ${record.serviceProjectName}`
		},
		{
			title: '订单金额',
			dataIndex: 'orderAmount',
			width: 80
		},
		{
			title: '定金金额',
			dataIndex: 'depositAmount',
			width: 80,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '尾款金额',
			dataIndex: 'balancePayment',
			width: 80,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '补款金额',
			dataIndex: 'payPayment',
			width: 80,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '剩余尾款金额',
			dataIndex: 'reduceBalancePayment',
			width: 110,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '服务时长',
			dataIndex: 'serviceLife',
			width: 80,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '赠送时长',
			dataIndex: 'giveMonth',
			width: 80,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '开始服务月',
			dataIndex: 'serviceStime',
			width: 120,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '结束服务月',
			dataIndex: 'serviceEtime',
			width: 120,
			customRender: ({ text }) => text || '-'
		}
	]
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		fixed: 'right',
		width: '100px'
	})
	/**
	 * 合同模板
	 */
	const templateOptions = ref([])
	const getTemplates = () => {
		contractApi.getBusinessTemplateList({}).then((res) => {
			templateOptions.value = res.map((item) => {
				return {
					label: item.templateName,
					value: item.templateId
				}
			})
		})
	}

	const searchType = ref(0)
	const searchText = ref('')
	const searchTextComputed = computed({
		get() {
			return searchText.value
		},
		set(val) {
			searchText.value = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const searchOption = ref({
		code: undefined,
		firstParty: undefined,
		createUser: undefined
	})
	/**
	 * 获取业务员搜索
	 */
	const userList = ref([])
	const searchKey = ref('')
	const saveUserList = ref([])
	const getCreaters = () => {
		const params = {
			searchKey: searchKey.value
		}
		contractApi.authUserSelector(params).then((res) => {
			userList.value = res.map((item) => {
				return {
					label: item.name,
					value: `${item.id}`
				}
			})
			saveUserList.value = JSON.parse(JSON.stringify(userList.value))
		})
	}
	let timeout
	const searchCreater = (value) => {
		if (timeout) {
			clearTimeout(timeout)
			timeout = null
		}
		userList.value = saveUserList.value.filter((v) => {
			return v.label.indexOf(value) !== -1
		})
	}
	const changeCreater = (value) => {
		if (!value) {
			userList.value = JSON.parse(JSON.stringify(saveUserList.value))
		}
	}
	/**
	 * 乙方信息列表获取
	 */
	const partyOptions = ref([])
	const getContractPartbList = () => {
		contractApi.getContractPartbList().then((res) => {
			partyOptions.value = res.map((item) => {
				return {
					value: item.id,
					label: item.partyName
				}
			})
		})
	}

	/**
	 * 更多筛选条件逻辑
	 */
	const screenVisible = ref(false)
	const labelCol = { style: { width: '100px' } }
	// 更多筛选条件初始值
	const moreDefaultSearch = {
		receivedOperators: 'eq',
		receivedAmount: null,
		signMethod: null,
		signPayment: null,
		templateId: null,
		financeApprovalStatus: null,
		signingDate: null,
		createDate: null,
		secondPartyId: null
	}
	const moreSearch = ref({ ...moreDefaultSearch })
	const clearSearch = () => {
		moreSearch.value = { ...moreDefaultSearch }
	}
	const doMoreSearch = () => {
		screenVisible.value = false
		table.value.refresh(true)
	}
	const cancelMoreSearch = () => {
		screenVisible.value = false
	}
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)
	const pageNum = ref(1)
	const pageSize = ref(10)

	/**
	 * 公共查询参数
	 */
	const getParams = (parameter = {}) => {
		if (searchType.value === 0) {
			searchOption.value.firstParty = searchText.value
			searchOption.value.code = null
		} else if (searchType.value === 1) {
			searchOption.value.firstParty = null
			searchOption.value.code = searchText.value
		}
		const params = {
			...searchOption.value,
			...moreSearch.value,
			...parameter
		}
		if (params.signingDate) {
			params.startSigningDate = params.signingDate[0]
			params.endSigningDate = params.signingDate[1]
			delete params.signingDate
		}
		if (params.createDate) {
			params.startCreateDate = params.createDate[0]
			params.endCreateDate = params.createDate[1]
			delete params.createDate
		}
		return params
	}

	/**
	 * 获取合同列表数据
	 */
	const loadData = (parameter) => {
		const params = getParams(parameter)
		return financePaymentApi.getPage(params).then((res) => {
			return res
		})
	}

	/**
	 * 查看凭证
	 */
	const imagePreviewRef = ref(null)
	const onPreview = (imgUrlStr) => {
		imgUrlStr &&
			imagePreviewRef.value.open({
				title: '查看付款凭证',
				tip: '凭证查看（点击图片查看大图）',
				list: imgUrlStr.split(',')
			})
	}

	/**
	 * 详情
	 */
	const onDetail = (id) => {
		const { localPagination } = table.value
		tableCache.set({
			searchType: searchType.value,
			searchText: searchText.value,
			searchOption: searchOption.value,
			moreSearch: moreSearch.value,
			pageNum: localPagination.current,
			pageSize: localPagination.pageSize
		})
		router.push(`/biz/financePayment/detail/${id}`)
	}

	/**
	 * 补款审批
	 */
	const approveVisible = ref(false)
	const info = ref({
		payment: {},
		paymentPay: {}
	})
	const approve = (row) => {
		financePaymentApi.getDetail({ id: row.id }).then((res) => {
			info.value = { ...row, ...res }
			approveVisible.value = true
		})
	}

	/**
	 * 批量导出
	 */
	const toBatchExport = () => {
		const params = getParams()
		financePaymentApi.exportList(params).then((res) => {
			downloadUtil.resultDownload(res)
		})
	}
</script>
<style lang="less" scoped>
	:deep(.ant-table-thead > tr > th::before) {
		width: 0 !important;
	}
	.center {
		text-align: center;
	}
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 350px);
	// }
</style>
